package nina.yiyou.salary.input.info

import nina.yiyou.salary.input.util.CellValueGetter
import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.IdMapMaker
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

/**
 * 读取社保表
 *
 * @see InsuranceExcelV2Reader
 */
@Deprecated
class InsuranceExcelReader {

  InsuranceExcelReader(String excelPath, Map<String, Object> basicMap) {
    _excelPath = excelPath
    _basicMap = basicMap
  }

  Map read() {
    Workbook workbook = new ExcelReadOpener(_excelPath).openXls()
    Sheet sheet = workbook.getSheetAt(0)
    Map idMap = new IdMapMaker(_basicMap).make()

    def result = (8..sheet.lastRowNum)
        .collect { sheet.getRow(it) }
        .collect { toLineMap(it) }
        .collect { [it, it[COLUMN_LIST[1][0]]] }
        .findAll { idMap.containsKey(it[1]) }
        .collectEntries { [idMap[it[1]], it[0]] }

    workbook.close()
    return result
  }

  private Map toLineMap(Row row) {
    def getColumn = { int col -> new CellValueGetter(row.getCell(col)).get() }

    def toEntry = { String key, int col, Class type ->
      Object value = getValue(getColumn(col), type)
      return [key, value]
    }
    return COLUMN_LIST.collectEntries(toEntry)
  }

  private Object getValue(Object raw, Class type) {
    if (type == double) {
      return Double.valueOf(raw as String)
    }
    return raw
  }

  private static final List<List> COLUMN_LIST = [
      ['姓名', 0, String],
      ['身份证号', 1, String],
      ['养老', 6, double],
      ['失业', 12, double],
      ['医疗', 15, double],
//      ['医疗', 18, double],
  ]

  private final String _excelPath

  private final Map<String, Object> _basicMap
}
